using Nekonya.Const;
using TinaX;
using TinaX.Utils;
using UnityEngine;

namespace Nekonya.Components
{
    [DisallowMultipleComponent]
    [RequireComponent(typeof(CharacterController))]
    public class PlayerCharacterController : MonoBehaviour
    {
        public CharacterController _CharacterController;

        public Transform _CameraTransform;
        public Camera _Camera;
        [Header("地面监测点")]
        public Transform _GroundCheckPoint;

        [Header("启动时锁定光标")]
        [Tooltip("如果勾选，在本组件运行时会锁定，可按取消键解锁")]
        public bool _LockCursorOnAwake = false;
        [Header("鼠标灵敏度")]
        public float _MouseSensitivity = 100f;
        [Header("移动速度")]
        public float _MoveSpeed = 12f;
        [Header("地面检测距离")]
        [Tooltip("模拟下落时，判断是否在地面上的判断球体的半径")]
        public float _GroundDistance = 0.4f;
        public LayerMask _GroundMask;
        [Header("跳跃高度")]
        public float _JumpHeight = 2f;
        [Header("模拟重力")]
        public float _Gravity = -10f;

        public bool EnablePlayerInput { get; set; } = true;


        private float m_XRotation = 0f;

        /// <summary>
        /// 速度
        /// </summary>
        private Vector3 m_Velocity;
        /// <summary>
        /// 我们在地面上吗
        /// </summary>
        private bool m_IsGrounded;


        private DisposableGroup m_DisposableGroup = new DisposableGroup();

        private void Awake()
        {
            m_DisposableGroup.RegisterEvent(EventConst.EnablePlayerControllerInput, _ =>
            {
                EnablePlayerInput = true;
                Cursor.lockState = CursorLockMode.Locked;
                Debug.Log("开始处理玩家操作输入");
            });

            m_DisposableGroup.RegisterEvent(EventConst.DisablePlayerControllerInput, _ =>
            {
                EnablePlayerInput = false;
                Cursor.lockState = CursorLockMode.None;
                Debug.Log("忽略玩家操作输入");
            });
        }


        private void Start()
        {
            if(_LockCursorOnAwake)
            {
                Cursor.lockState = CursorLockMode.Locked;
            }
        }

        private void Update()
        {
            #region 视角旋转处理

            if (EnablePlayerInput)
            {
                float mouseX = Input.GetAxis("Mouse X") * _MouseSensitivity * Time.deltaTime;
                float mouseY = Input.GetAxis("Mouse Y") * _MouseSensitivity * Time.deltaTime;

                m_XRotation -= mouseY;
                m_XRotation = Mathf.Clamp(m_XRotation, -90f, 90f);

                _CameraTransform.localRotation = Quaternion.Euler(m_XRotation, 0f, 0f);

                this.transform.Rotate(Vector3.up * mouseX);
            }

            #endregion

            #region 角色移动
            if (EnablePlayerInput)
            {
                var moveX = Input.GetAxis("Horizontal");
                var moveZ = Input.GetAxis("Vertical");

                //m_IsGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
                Vector3 move = transform.right * moveX + transform.forward * moveZ;
                _CharacterController.Move(move * _MoveSpeed * Time.deltaTime);
            }
            #endregion

            #region 跳跃与模拟重力
            bool jumpPressed = EnablePlayerInput ? Input.GetButtonDown("Jump") : false;
            m_IsGrounded = Physics.CheckSphere(_GroundCheckPoint.position, _GroundDistance, _GroundMask);
            if (m_IsGrounded && m_Velocity.y < 0)
            {
                m_Velocity.y = -2f;
            }
            //if (jumpPressed)
            //{
            //    Debug.Log("按下了跳跃");
            //}
            if (jumpPressed && m_IsGrounded)
            {
                Debug.Log("跳跃?");
                m_Velocity.y = Mathf.Sqrt(_JumpHeight * -2f * _Gravity); //平方根
            }

            m_Velocity.y += _Gravity * Time.deltaTime;
            _CharacterController.Move(m_Velocity * Time.deltaTime);
            #endregion
        }



        private void OnDestroy()
        {
            m_DisposableGroup?.Dispose();
        }
    }
}
